package es

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"strings"
)

func EsVideo(title string) VideoEs {
	es := EsClient
	video := map[string]interface{}{
		"query": map[string]interface{}{
			"match": map[string]interface{}{
				"VideoTitle": title,
			},
		},
		"highlight": map[string]interface{}{
			"fields": map[string]interface{}{
				"VideoTitle": map[string]interface{}{
					"pre_tags":  []string{"<em>"},
					"post_tags": []string{"</em>"},
				},
			},
		},
	}
	marshal, _ := json.Marshal(video)
	res, err := es.Search(
		es.Search.WithContext(context.Background()),
		es.Search.WithIndex("video"),
		es.Search.WithBody(strings.NewReader(string(marshal))),
		es.Search.WithTrackTotalHits(true),
		es.Search.WithPretty(),
	)
	if err != nil {
		log.Fatalf("ERROR: %s", err)
	}
	defer res.Body.Close()
	fmt.Println("1111", res)

	if res.IsError() {
		var e map[string]interface{}
		if err := json.NewDecoder(res.Body).Decode(&e); err != nil {
			log.Fatalf("error parsing the response body: %s", err)
		} else {
			// Print the response status and error information.
			log.Fatalf("[%s] %s: %s",
				res.Status(),
				e["error"].(map[string]interface{})["type"],
				e["error"].(map[string]interface{})["reason"],
			)
		}
	}
	var App VideoEs
	json.NewDecoder(res.Body).Decode(&App)
	fmt.Println("2222", App)
	return App
}

type VideoEs struct {
	Took     int  `json:"took"`
	TimedOut bool `json:"timed_out"`
	Shards   struct {
		Total      int `json:"total"`
		Successful int `json:"successful"`
		Skipped    int `json:"skipped"`
		Failed     int `json:"failed"`
	} `json:"_shards"`
	Hits struct {
		Total struct {
			Value    int    `json:"value"`
			Relation string `json:"relation"`
		} `json:"total"`
		MaxScore float64 `json:"max_score"`
		Hits     []struct {
			Index  string  `json:"_index"`
			Type   string  `json:"_type"`
			Id     string  `json:"_id"`
			Score  float64 `json:"_score"`
			Source struct {
				Id           string `json:"id"`
				VideoTitle   string `json:"VideoTitle"`
				VideoName    string `json:"VideoName"`
				VideoAddress string `json:"VideoAddress"`
				VideoSort    int    `json:"VideoSort"`
				VideoPro     string `json:"VideoPro"`
			} `json:"_source"`
			Highlight struct {
				VideoTitle []string `json:"VideoTitle"`
			} `json:"highlight"`
		} `json:"hits"`
	} `json:"hits"`
}
